<script setup lang="ts">
import { ref, onMounted,reactive, UnwrapRef, computed } from 'vue'
import { teachHomeworkList, teachHomeworkDeleted } from '../../stores/api/homework'
import { useCounterStore } from '../../stores/counter'
import { useRoute, useRouter } from "vue-router";
import type { TableProps } from 'ant-design-vue';
import { ImgUrlPrefix } from '../../utils/config'
import {  QuestionCircleOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
const store = useCounterStore()
const router:any = useRouter()
const route:any = useRoute()
const loading = ref(false)
const type = ref<string>('')
const id = ref('')
const isShowAttachment = ref(false)
const attachment = ref([])
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',   
    width: 90
  },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    width: 150
  },
  {
    title: '班级名称',
    dataIndex: 'classes',
    key: 'classes'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '附件',
    dataIndex: 'attachment',
    key: 'attachment',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },
  {
    title: '提交截止时间',
    dataIndex: 'deadline',
    key: 'deadline',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
];
const data_list = ref([])

interface FormState {
  title: string;
  status: string;
  type: string;
}
const formState: UnwrapRef<FormState> = reactive({
  title: '',
  status: '', 
  type: ''
});

// 作业列表
const getCourseList = () => {
    loading.value = true
    teachHomeworkList({ page:  pagination.current, title: formState.title, status: formState.status, id: Number(route.query.class_id)}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            data_list.value = res.data.items
            pagination.total = res.data.total
        }
        loading.value = false
    }).catch((err: any) => {
        console.log(err)
        loading.value = false
    })
}

const homeworkList = computed(() => {
  return data_list.value.map(item => {
       return { ...item, attachment: item.attachment ? JSON.parse(item.attachment) : '',created_at: store.timestampChangDate(item.created_at * 1000), deadline: store.timestampChangDate(item.deadline * 1000) }
  })
})

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}

// 截取字符串
const getExtractString = (val) => {
    if(val) {
        const startIndex = val.lastIndexOf('/') + 1
        const url = val.substring(startIndex);
        return url
    } else{
        return ''
    }
}

// 查看更多
const seeMore = (val) => {
    isShowAttachment.value = true
    attachment.value = val.attachment
}

// 搜索
const onSubmit = () => {
    getCourseList()
}
// 取消
const onCancel = () => {
    formState.title = ''
    formState.status = ''
    formState.type = ''
    getCourseList()
}
// 新增
const getAdd = () => {
    // isShowAdd.value = true
    type.value = 'add'
    router.push({path: '/assignHomework', query: { id: '', class_id: Number(route.query.class_id),course_id: Number(route.query.course_id) }})
}
const handleTableChange: TableProps['onChange'] = (
  pag: { pageSize: number; current: number }
) => {
  console.log(pag?.current)
  pagination.current = pag?.current
  getCourseList()
};

// 更新
const handleUpdate = (val:any) => {
    type.value = 'edit'
    // isShowAdd.value = true
    id.value = val.id
    router.push({path: '/assignHomework', query: { id: val.id, class_id: Number(route.query.class_id),course_id: Number(route.query.course_id), data: JSON.stringify(val) }})
}

// 删除
const handleDelete = (id:any) => {
    console.log('删除',id)
    teachHomeworkDeleted({
        "id": id
    }, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('删除成功');
            getCourseList()
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 下载
const onDownload = (item:any) => {
    let val = getImgUrl(item)
    window.open(val, '_blank');
}
onMounted(() => {
    getCourseList()
    console.log('route.query.p_id',route.query.class_id,route.query.course_id)
})
</script>

<template>
    <div class="courseDetails">
        <a-page-header
            style="border: none;padding: 0"
            title="作业"
            sub-title=""
            @back="() => $router.go(-1)"
        />
        <div class="list-box">
            <div class="form-filter">
                <a-button type="primary" class="btn-sub" @click="getAdd">发布</a-button>
                <a-form layout="inline" :model="formState">
                    <a-form-item label="标题">
                        <a-input v-model:value="formState.title" placeholder="请输入标题" />
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-select v-model:value="formState.status" placeholder="请选择状态" style="width: 130px">
                            <a-select-option :value="10">进行中</a-select-option>
                            <a-select-option :value="20">已结束</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item>
                        <a-button type="primary" class="btn-ss" @click="onSubmit">搜索</a-button>
                        <a-button style="margin: 0 20px;" @click="onCancel">取 消</a-button>
                    </a-form-item>
                </a-form>
            </div>
            <a-table :columns="columns" :pagination="pagination" :scroll="{ x: 1500}"
                :loading="loading" :data-source="homeworkList" @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    
                    <template v-if="column.key === 'id'">
                        <span>
                        {{ record.id }}
                        </span>
                    </template>
                    <template v-if="column.key === 'title'">
                        <span>
                        {{ record.title }}
                        </span>
                    </template>
                    <template v-if="column.key === 'classes'">
                        <span>
                        {{ record.classes && record.classes.name ? record.classes.name : ''}}
                        </span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <span>
                            <a-tag color="green" v-if="record.status == 10">进行中</a-tag>
                            <a-tag color="cyan" v-else-if="record.status == 20">已结束</a-tag>
                            <span v-else>--</span>
                        </span>
                    </template>
                    <template v-else-if="column.key === 'attachment'">
                        <span v-if="record.attachment.length > 1">
                            <a @click="seeMore(record)">查看更多</a>
                        </span>
                        <span v-else>
                            <a :href="getImgUrl(item)" v-for="item in record.attachment" :key="item" rel="noopener noreferrer"> {{  getExtractString(item) }}</a>
                        </span>
                    </template>
                    <template v-if="column.key === 'created_at'">
                        <span>
                        {{ record.created_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'deadline'">
                        <span>
                        {{ record.deadline || '--' }}
                        </span>
                    </template>
                    <!-- <template v-if="column.key === 'desc'">
                        <a-tooltip placement="top" v-if="record.desc.length > 40">
                            <template #title>
                                 <span>{{ record.desc }}</span>
                            </template>
                            <span>
                               {{ record.desc }}
                            </span>
                        </a-tooltip>
                        <span v-else>
                            {{ record.desc }}
                        </span>
                    </template> -->
                    <template v-else-if="column.key === 'action'">
                        <span style="margin-right: 10px">
                          <a @click="handleUpdate(record)">编辑</a>
                        </span>
                        <span>
                            <a-popconfirm title="是否删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record.id)"> 
                                <template #icon><question-circle-outlined style="color: red" /></template>
                                <a>删除</a>
                            </a-popconfirm>
                        </span>
                    </template>
                </template>
            </a-table>
        </div>
        <!-- <a-modal v-model:open="isShowAdd" :title="'用户列表'" width="700px" ok-text="" cancel-text="" @cancel="resetForm" :footer="null">
            <div class="live-left">
                <a-table :columns="user_columns" :pagination="pagination2"
                    :loading="user_loading" :data-source="user_list" @change="handleTableChange2">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'id'">
                            <span>
                                {{ record.id }}
                            </span>
                        </template>
                        <template v-if="column.key === 'nick_name'">
                            <span>
                               {{ record.nick_name }}
                            </span>
                        </template>
                        <template v-else-if="column.key === 'action'">
                            <span style="margin-right: 10px">
                               <a @click="handleSee(record)">查看</a>
                            </span>
                        </template>
                    </template>
                </a-table>
            </div>
        </a-modal> -->
        <a-modal v-model:open="isShowAttachment" :title="'附件'" width="700px" ok-text="" cancel-text="" :footer="null">
            <div class="live-left">
                <!-- <div v-for="item in attachment" :key="item">
                    <a :href="getImgUrl(item)" rel="noopener noreferrer"> {{  getExtractString(item) }}</a>
                </div> -->
                <div v-for="(item, index) in attachment" :key="index" style="display: flex;flex-wrap: wrap;margin-top: 20px;">
                    <div>{{ index == 0 ? '图片素材：': '其他附件：'}}</div>
                    <div>
                        <div v-if="index == 0">
                            <img class="image-material" :src="getImgUrl(m)" alt="" v-for="(m, idx) in item" :key="idx">
                        </div>
                        <!-- <a v-else :href="getImgUrl(m)" target="_blank" v-for="(m, idx) in item" :key="idx" rel="noopener noreferrer"> {{  getExtractString(m) }}</a> -->
                        <div v-else  v-for="(m, idx) in item" :key="idx">
                            <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(m) }}</span>
                            <a-tag color="default" style="cursor: pointer;" @click="onDownload(m)" v-if="m">下载</a-tag>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<style scoped>
.courseDetails{
    padding: 15px;
}
.top-content-p{
    background-color: #fff;
    /* padding: 10px 15px;
    border-radius: 6px; */
}
.title-item-p{
    line-height: 40px;
    font-weight: bold;
    font-size: 16px;
}
.content-box{
    display: flex;
    flex-wrap: wrap;
    margin: 6px 0;
}
.name-item{
    line-height: 36px;
    min-width: 200px;
    color: #333;
    margin-right: 50px;
}
.name-item span{
    color: #000;
    margin-left:4px;
}
.content-ssv{
    color: #000;
    margin-left:4px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 32px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.btn-sub{
    background-color: #87d068;
    height: 32px;
}
.btn-sub:hover{
    background-color: #87d068;
}
.list-box{
    margin-top: 15px;
}

.form-filter{
   margin: 20px 0;   
   display: flex;
   justify-content: space-between;
}
.thumbnail_{
    width: 80px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 130px;
    height: 132px;
    line-height: 26px;
    text-align: center;
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}

.image-material{
    width: 120px;
    height: 120px;
}
</style>
